<?php

namespace app\common\controller;

use app\BaseController;
use app\common\service\UserAuthService;
use app\common\traits\UapiJumpTrait;

class ApiController extends  BaseController
{
    use UapiJumpTrait;

    /**
     * 控制器方法是否登录
     * @var bool
     */
    public static $needLoginAction = [];

    /**
     * 用户信息
     * @var array
     */
    public $userInfo = [];

    public $user_id = 0;
    /**
     * 初始化方法
     */
    protected function initialize()
    {
        parent::initialize();

        //用户信息
        $this->userInfo = $this->request->userInfo;
        $this->user_id = $this->userInfo['id'] ?? 0;

        $this->checkAuth();
    }


    /**
     * 检测权限
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function checkAuth()
    {

        $currentController = parse_name(app()->request->controller());
        $currentAction = app()->request->action();
        /* @var UserAuthService $UserAuthService */
        $UserAuthService = app(UserAuthService::class, ['controller' => $currentController, 'action' => $currentAction,'module'=>'uapi']);

        $is_pass = $UserAuthService->checkAction();
        if (!$is_pass) {
            $user = $this->userInfo;
            if (empty($user)) {

                $this->error('请先登录', [],401);
            }
        }
    }
    /**
     * 重写验证规则
     * @param array $data
     * @param array|string $validate
     * @param array $message
     * @param bool $batch
     * @return array|bool|string|true
     */
    public function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        try {
            parent::validate($data, $validate, $message, $batch);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        return true;
    }

    /**
     * 严格校验接口是否为POST请求
     */
    protected function checkPostRequest()
    {
        if (!$this->request->isPost()) {
            $this->error("当前请求不合法！");
        }
    }

}